package com.dq.protocol;

import com.dq.common.Invocation;
import com.dq.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName HttpServletHandler
 * @Description 集中处理
 * @Author DuX1aoQiang
 * @Date 2023/5/24 11:46
 * @Version 1.0
 */
public class HttpServletHandler {
    protected void handler(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求 干嘛的   只能获取接口 方法 方法参数  利用Invocation存储
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            String interfaceName = invocation.getInterfaceName();
            //读取默认版本号
            Class clazzImpl = LocalRegister.get(interfaceName, "1.0");
            Method method = clazzImpl.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            String result = (String) method.invoke(clazzImpl.newInstance(), invocation.getParameters());

            //把结果写入res中去
            IOUtils.write(result, resp.getOutputStream());

        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException |
                 InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    }
}
